package payment

import (
	"cloud_android_backend/pkg/models/orders"
	"cloud_android_backend/pkg/models/products"
	"cloud_android_backend/pkg/models/resources"
	"cloud_android_backend/pkg/models/users"
	"cloud_android_backend/pkg/modules/realphone"
	"github.com/golang/glog"
	"github.com/jinzhu/gorm"
	"modules.tenxcloud.com/common/composite"
	"strconv"
	"time"
)

type Trial struct {
	Amount  float64
	UserId  string
	OrderId int64
}

func (b *Trial) Payment() (string, error) {
	db, err := composite.Database.GetOrm()
	if err != nil {
		glog.Errorf("get orm failed, error %v", err)
		return "", err
	}
	//userModel := user.User{UserID: b.UserId}
	err = db.Transaction(func(tx *gorm.DB) error {

		orderModel := orders.Orders{Id: b.OrderId}
		if err := orderModel.GetById(db); err != nil {
			glog.Errorf("查询订单失败: %v", err)
			return err
		}
		orderModel.PayTime = time.Now()
		orderModel.ActualAmount = 0
		orderModel.CallbackTime = time.Now()
		orderModel.Status = int(orders.OrderStatus_Success)

		err = orderModel.Update(tx)
		if err != nil {
			glog.Errorf("更新订单失败: %v", err)
			return err
		}
		packageInfo := products.ProductPackages{Id: orderModel.PackageId}
		err = packageInfo.GetById(db)
		if err != nil {
			glog.Errorf("get product package info failed:err %v", err)
			return err
		}
		instanceModel := resources.InstanceUses{OrderId: orderModel.Id}
		instanceList, err := instanceModel.GetListByOrderId(tx)
		if err != nil {
			glog.Errorf("get instance use list failed:err %v", err)
			return err
		}
		for _, instance := range instanceList {
			instanceModel := &instance
			instanceModel.Status = int(resources.InstanceUseStatusUsing)
			instanceModel.StartTime = time.Now()
			instanceModel.ExpireTime = time.Now().Add(30 * time.Minute)
			instanceModel.InstanceName = "云机" + strconv.FormatInt(instanceModel.Id, 10)
			instanceModel.IsTrial = 1
			err = instanceModel.Update(tx)
			if err != nil {
				glog.Errorf("update instance use failed:err %v", err)
				return err
			}

			go func(id int64) {
				if err := realphone.EasyToRecreateNewInstance(id, b.UserId); err != nil {
					glog.Error(err)
				}
			}(instance.Id)
		}
		userModel := users.User{UserID: b.UserId}
		err = userModel.GetByUserId(db)
		if err != nil {
			glog.Errorf("get user failed:err %v", err)
			return err
		}
		//userModel.UsedTrialCoupon = 1
		err = userModel.UpdatePartFields(db, map[string]interface{}{"used_trial_coupon": 1})
		if err != nil {
			glog.Errorf("update user failed:err %v", err)
			return err
		}

		//go instances.InstanceConnect(instanceList)

		return nil
	})
	if err != nil {
		glog.Errorf("transaction failed:err %v", err)
		return "", err
	}
	return "", nil
}

func (b *Trial) GetResultType() ResultType {
	return ""
}
func (b *Trial) GetResult() string {
	return ""
}
